package br.ufpb.di.knowledgetv.sqtv.modules;

import br.ufpb.di.knowledgetv.sqtv.inference.builtins.CompareString;
import br.ufpb.di.knowledgetv.sqtv.utils.Data;
import com.hp.hpl.jena.rdf.model.InfModel;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.reasoner.Reasoner;
import com.hp.hpl.jena.reasoner.rulesys.BuiltinRegistry;
import com.hp.hpl.jena.reasoner.rulesys.GenericRuleReasoner;
import com.hp.hpl.jena.reasoner.rulesys.Rule;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * User: Manoel
 * Date: 11/04/13
 */

@Component
public class ResultAlignmentModule implements SQTVModule {

    Logger logger = Logger.getLogger(ResultAlignmentModule.class);

    @Override
    @SuppressWarnings("unchecked")
    public Data execute(Data data) {

        Model result = ModelFactory.createDefaultModel();

        String rulesStr = "";
        try {
            File file = new File(getClass().getResource("/inference/rules/instance_alignment_rules.rl").getFile());
            rulesStr = FileUtils.readFileToString(file);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        BuiltinRegistry.theRegistry.register(new CompareString());
        List<Rule> rules = Rule.parseRules(rulesStr);
        Reasoner reasoner = new GenericRuleReasoner(rules);

        for(Model modelData : (ArrayList<Model>)data.getData("models")) {
            InfModel infModel = ModelFactory.createInfModel(reasoner, modelData);
            result.add(infModel);
        }

        data.addData("result_model", result);
        return data;
    }
}
